// pages/recommend/recommend.js
import api from '../../utils/api.js'
import { config } from '../../utils/config'
import {
    HTTP
} from '../../utils/http.js'
const http = new HTTP()
var app = getApp()
const ret = []

var sss = []
let shopId = null; //商铺id
const unitZn = { //中文单位
    0: "kg",
    1: "份",
    2: "箱",
    3: "包",
    4: "袋",
    5: "斤"
}
Page({
    /**
     * 页面的初始数据
     */
    data: {
        height: app.globalData.height * 2 + 20,
        hidden: [false, false, false, false, false], //伸缩展开
        animationArr: [], //动画
        scrollDown: 0,
        singleShop: [], //店铺头部信息
        singleShopMenus: [], //单个店铺可卖菜谱
        singleDetail: [], //菜谱有几种食材-分类
        myAllItem: [], // 组合接口后的 食材种类
        distance: '', //距离
        totalPrice: [], //单个菜谱合计总价
        totalMoney: 0,
        selected: false,
        localItem: [],
        showModel: false, //结算 按钮的模态窗口
        showDetail: false, //展示 详情
        productDetail: [], // 产品全部信息
        details: [], // 地区信息
        replaceCookbooks: [],
        imgUrl: config.imgUrl,
    },
    // 菜篮操作
    add(e) {
        let self = this;
        const faIndex = e.currentTarget.dataset.findex; //父级index
        const tIndex = e.currentTarget.dataset.tindex; //点击菜谱是最高tindex
        const name = e.currentTarget.dataset.name; //菜谱名称
        const classes_id = e.currentTarget.dataset.classes_id; // 三级分类，土豆，肋排id
        const product_id = e.currentTarget.dataset.product_id; //单一商品的 id

        // 获取商品数据
        let list = this.data.myAllItem[tIndex];
        // console.log('父级菜谱索引', tIndex)
        // console.log('22222222', list)
        // 给 当前 子项增加商品数量: num 属性
        list.forEach((ele) => {
            // console.log('外层', ele)
            if (ele.classes_id == classes_id) { //验证外层分类id 是否等于 单品分类id  129
                if (ele.son) { //若没有三级单品，则跳过，不报错
                    ele.son.forEach((ele) => {
                        // console.log('内层', ele)
                        if (ele.product_id == product_id) {
                            self.judgeproductStock(ele);

                        } else {
                            ele.mark = false
                        }
                    })
                }

            }

        });

        let myAllItem = 'myAllItem' + '[' + tIndex + ']'
        this.setData({
            [myAllItem]: list
        });
        this.totalPrice(e); //计算总价
        this.checkMenus(e); //确定选择的菜单
    },
    reduce(e) {
        const index = e.currentTarget.dataset.index;
        const name = e.currentTarget.dataset.name;
        const product_id = e.currentTarget.dataset.product_id;
        const faIndex = e.currentTarget.dataset.findex; //父级index
        const tIndex = e.currentTarget.dataset.tindex; //点击菜谱是最高tindex
        // 获取商品数据
        let list = this.data.myAllItem[tIndex]; //当前点击的菜谱
        // 控制 商品数量
        list.forEach((ele) => {
            if (ele.son) { //若没有三级单品，则跳过，不报错
                ele.son.forEach((ele) => {
                    if (ele.product_id == product_id) {
                        ele.num -= 1
                        ele.mark = true
                        if (ele.num == 0) {
                            ele.mark = false
                        }
                    }
                })
            }

        });
        let myAllItem = 'myAllItem' + '[' + tIndex + ']'
        this.setData({
            [myAllItem]: list
        });
        this.totalPrice(e); //计算总价
        this.checkMenus(e); //确定选择的菜单
    },
    // 单品 库存判断
    judgeproductStock(ele) {
        if (ele.num == ele.stock) {
            wx.showToast({
                title: '已经达到该商品的最大库存了',
                icon: "none",
                duration: 1500,
                mask: true,
                success: () => {}
            })
        } else {
            ele.num += 1
            ele.mark = true;
        }
    },
    /**
     * 计算单个菜谱合计总价
     */
    totalPrice(e) {
        var price = 0
        let tindex = e.currentTarget.dataset.tindex; //菜谱index
        let myAllItem = this.data.myAllItem;

        myAllItem[tindex].forEach((ele) => {
                if (ele.son) {
                    ele.son.forEach((sonItem) => {
                        if (sonItem.mark) {
                            price += (sonItem.num * sonItem.price)
                        }
                    })
                }

            })
            // price = price.toFixed(2)

        let totalPrice = this.data.totalPrice;
        totalPrice[tindex] = price

        this.setData({
            totalPrice
        });
        this.totalMoney()
    },
    totalMoney() {
        let totalMoney = 0;
        let totalPrice = this.data.totalPrice;

        totalPrice.forEach((ele) => {
            totalMoney += ele
        })

        this.setData({
            totalMoney
        })

    },
    //判断菜谱是否被选择check: 0 1 
    //0: 一个都没有 1: 有一类 就可以
    checkMenus(e) {
        const faIndex = e.currentTarget.dataset.findex; //父级index
        let tIndex = e.currentTarget.dataset.tindex; //菜谱顶级index

        let singleShopMenus = this.data.singleShopMenus;
        let myAllItem = this.data.myAllItem;

        // 获取商品数据
        let list = this.data.myAllItem[tIndex];

        console.log('当前点击单品的菜单', list)
            //食材任意一项
        let stateMenu = list.some((ele, index) => {
            if (ele.son) {
                return ele.son.some(function(ele, index) {
                    return ele.mark == true
                })
            }

        })
        console.log('stateMenu', stateMenu)
        if (stateMenu) {
            singleShopMenus[tIndex].check = 1
            this.setData({
                singleShopMenus: singleShopMenus
            })

        } else {
            singleShopMenus[tIndex].check = 0
            this.setData({
                singleShopMenus: singleShopMenus
            })

        }

    },
    recommendOrder(e) { //下单
        let myCook = this.myFilter() //调用下方组合菜谱方法
        console.log('myCook', myCook)
        this.userMenus()
        let totalMoney = this.data.totalMoney
        let shopAddress = this.data.singleShop.address;
        if (totalMoney == 0) {
            wx.showToast({
                title: '您还未选择任何商品！',
                icon: 'none',
                mask: true
            })
            return false
        } else {
            // 依据标识符 —— 过滤单品
            for (var i = 0; i < myCook.length; i++) {
                myCook[i].product = myCook[i].product.filter((item) => {
                    return item.mark == true
                })
            }
            wx.setStorageSync("myCook", myCook);
            var recommendSelectedItem = sss.filter((ele, i) => {
                return ele.mark == true
            })

            wx.setStorageSync("recommendSelectedItem", recommendSelectedItem);
            wx.navigateTo({
                url: `/pages/recommendOrder/recommendOrder?totalMoney=${totalMoney}&shopId=${shopId}&menuType=1&shopAddress=${shopAddress}`,
                success: function() {
                    console.log('清空过渡数组！！！')
                    sss = []
                }
            })
        }

    },
    myFilter() {
        //myAllItem可能未被获取，未点击时，没有调用接口，为null
        let selectedList = this.data.myAllItem; //菜谱对应的食材种类
        let singleShopMenus = this.data.singleShopMenus; // 当前店铺可售卖的菜谱
        let myCook = []
        let product = []


        // selectedList = selectedList.filter((ele) => {
        //   if (ele != undefined || ele != null) { //去除选择菜单时，单项为undefined的可能性
        //     return true
        //   }
        // })

        //用户在哪个菜谱下，购买了食材
        let userMenus = singleShopMenus.filter((ele) => {
            return ele.check === 1
        })
        wx.setStorageSync('userMenus', userMenus)
        console.log('所有点击展开的菜谱selectedList', selectedList)

        //选择的菜谱的索引值——要对应食材种类的索引
        singleShopMenus.forEach((ele, index) => {
                product[index] = [] //非常重要 ，以菜谱索引
                if (ele.check === 1) {
                    // console.log('iiiiiiiii', index)
                    selectedList[index].forEach((sEle, sIndex) => {
                        if (sEle.son) {
                            sEle.son.forEach((min) => {
                                // console.log('mmmmmmmmmm', min)
                                product[index].push(min)
                            })
                        }
                    })

                    myCook.push({
                        cook_name: ele.name,
                        cook_id: ele.id,
                        product: product[index]
                    })
                }

            })
            // console.log('myCook', myCook)


        //下一步 的 食材 处理
        for (let item of selectedList) { //迭代
            if (item instanceof Object) {
                item.forEach((ele) => {
                    if (ele.son) {
                        ele.son.forEach((inner) => {
                            // console.log('内内内内', inner)
                            sss.push(inner)
                        })
                    }

                })
            }

        }
        console.log('下单时过渡数组', sss)

        return myCook;
    },

    userMenus() { //下单操作时，传给下个页面当前页面已选菜谱
        let singleShopMenus = this.data.singleShopMenus;
        singleShopMenus = singleShopMenus.filter((ele) => {
            return ele.check === 1
        })
        console.log('用户在筛选店铺页面-选择的菜谱', singleShopMenus)
        wx.setStorageSync('userMenus', singleShopMenus)
    },

    // 展示 商品 详情
    showDetail(e) {

        let showDetail = this.data.showDetail;
        let showModel = this.data.showModel;
        let product_id = e.currentTarget.dataset.product_id
        http.request({
            url: api.getOnE,
            method: "POST",
            data: {
                id: product_id,
            },
            success: (res) => {
                const data = res.data;
                const details = JSON.parse(data.details)
                if (res.code == 200) {
                    this.setData({
                        productDetail: data,
                        details: details
                    })
                    this.setData({
                        showDetail: !showDetail,
                        showModel: !showModel
                    })
                }

            },
            fail: (res) => {
                console.log('error', res)

            }
        })

    },
    close(e) {
        this.setData({
            productDetail: [],
            details: [],
            showDetail: false,
            showModel: false
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        console.log('选择食材的 options', options)
        let that = this;
        let index = options.index
        let sid = options.shopId //商铺id

        shopId = sid

        let selectedMenuId = this.getSelectedMenuId()
            // console.log('用户所购买的菜谱ID', selectedMenuId)

        //进入单个店铺头部信息
        if (options) {
            let shopList = wx.getStorageSync('shopList')
            shopList = shopList.filter((ele) => {
                return ele.id == sid
            })
            this.toDistanceFixed(shopList[0].distance)
            wx.setStorageSync('singleShopList', shopList[0]) //当前进入店铺的信息
                // console.log('shopList[0].distance', shopList[0].distance)
            this.setData({
                singleShop: shopList[0]
            })
        }

        //商铺可以售卖的菜谱列表
        http.request({
            url: api.shopBooks,
            method: "POST",
            data: {
                id: shopId, //商户id
                uoids: selectedMenuId //菜谱id
            },
            success: (res) => {
                if (res.code == 200) {
                    let data = res.data
                    data.map((ele) => {
                        return ele.clc = 0;
                    })
                    data.map((ele) => {
                        return ele.open = false;
                    })

                    that.setData({
                            singleShopMenus: data,
                        })
                        //回调 菜谱的 二级 分类
                    that.getCookClass(shopId);
                }
            },
            fail: (res) => {
                console.log('error', res)
            }
        })

    },
    //查找单个或者多个菜谱对应的食品分类
    getCookClass(shopId) {
        let that = this;
        //拿到店铺实际可以售卖的菜谱id
        let singleShopMenus = this.data.singleShopMenus;
        let ids = [];
        singleShopMenus.forEach((ele, i) => {
                ids.push(ele.id)
            })
            // console.log('店铺实际可以售卖的菜谱ids', ids)
        ids = ids.join(","); //传参设置

        http.request({
            url: api.getCookClass,
            method: "POST",
            data: {
                ids: ids, //多个菜谱id
            },
            success: (res) => {
                const data = res.data;
                console.log('getCookClass', data)
                let guodu = []
                if (data) {
                    data.forEach((ele) => {
                        guodu.push(ele)
                    })
                    that.setData({
                            singleDetail: guodu
                        })
                        // that.foldList(null, 0, 0, 0)
                }
            },
            fail: (res) => {
                console.log('error', res)

            }
        })
    },
    // 确定小分类下商户能卖的商品以及对应的价格
    getThreeProducts(id, shopId, menuid) {
        return new Promise(function(resolve, reject) {
            http.request({
                url: api.getThreeProducts,
                method: "POST",
                data: {
                    id: id, //单个商品id
                    sid: shopId, //商家id
                    cookbook_id: menuid
                },
                success: (res) => {
                    if (res.code == 200) {
                        const data = res.data
                            // 给 当前 子项增加商品数量: num 属性
                        data.forEach((ele) => {
                            ele.num = 0
                        })
                        resolve(data);
                    } else if (res.code == 401) {
                        const data = res.data
                            //当前菜谱缺失主料，取公网数据展示缺失的主料
                        data.forEach((ele) => {
                            ele.missing = true
                        })
                        if (data.length == 0) {
                            data.push({
                                missing: true
                            })
                        }
                        resolve(data);
                    } else if (res.code == 402) {
                        const data = res.data
                            //公网辅材数据不展示
                        if (data.length == 0) {
                            data.push({
                                missing: true
                            })
                        }
                        resolve(data);
                    } else if (res.data.error_code == 201) {
                        console.log('该分类下 暂无食材')
                        reject(res.data)
                    }
                },
                fail: (res) => {
                    console.log('error', res)
                }
            })
        })
    },
    //保留小数
    toDistanceFixed(str) {
        str = str.toFixed(2)
        this.setData({
            distance: str
        })
    },
    getSelectedMenuId() {
        //本地存储——已选菜谱id
        let menusId = [];
        let selectedMenus = wx.getStorageSync('select-menus')
        selectedMenus = selectedMenus.filter((ele, i) => {
            return ele.flag == true
        })
        selectedMenus = selectedMenus.filter((ele, i) => {
            return ele.greyOff != true
        })
        selectedMenus.forEach((ele, i) => {
            menusId.push(ele.id)
        })

        return menusId.join(",")
    },

    foldList(e, myClc, myIndex, myIdx) {
        console.log('z折叠', e)
        let menuid = e.currentTarget.dataset.menuid;
        console.log('myClc', myClc)
        let clc, meunIndex, idx;
        let localItem = this.data.localItem;
        if (myClc == 0) {
            clc = myClc
        } else {
            clc = e.currentTarget.dataset.first; //折叠防止重复请求
        }

        let that = this;
        if (myIndex == 0) {
            meunIndex = myIndex
        } else {
            meunIndex = e.currentTarget.dataset.index; // wxml内 点击菜谱对应的索引值
        }

        let currentProductId = [];
        let mainProductId = []; //主食材id
        let minorProductId = []; //辅食材id
        let repalceId = []; // 主食材id
        let typeclasses = this.data.singleDetail[meunIndex].typeclasses; //菜谱配料-分类
        console.log('typeclasses', typeclasses)

        typeclasses.forEach((item, i) => {
                currentProductId.push(item.classes_id)
                    //单品分类的id -循环请求,新增区分主材与辅材
                if (item.classes_type == 0) { //增加主食材id
                    mainProductId.push(item.classes_id)
                    repalceId.push(item.classes_id)
                } else if (item.classes_type == 1) {
                    minorProductId.push(item.classes_id)
                }
            })
            //显示隐藏
        if (myIdx == 0) {
            idx = myIdx
        } else {
            idx = e.currentTarget.dataset.index;
        }


        var memberList = this.data.singleShopMenus;
        for (let i = 0; i < memberList.length; i++) { // 展开收缩判断
            if (idx == i) {
                memberList[i].open = !memberList[i].open;

            }
            //  else {
            //   memberList[i].open = false;
            // }
        };
        this.setData({
            singleShopMenus: memberList
        });

        if (clc == 0) {
            let singleShopMenus = this.data.singleShopMenus
            singleShopMenus[meunIndex].clc = 1
            this.setData({
                    singleShopMenus: singleShopMenus
                })
                //依据接口，遍历所有的单品id——循环请求
            let promises = currentProductId.map((i, num) => {
                //可售卖菜谱
                return that.getThreeProducts(i, shopId, menuid)
            })
            Promise.all(promises).then((allData) => {
                    allData.forEach((res, num) => {
                        if (res[0].missing && res[0].missing == true) {
                            typeclasses[num].missing = true
                                // repalceId = repalceId.filter((ele) => {
                                //   return ele !== i
                                // })
                        } else {
                            typeclasses[num].missing = false
                        }
                        typeclasses[num].son = res
                        localItem[meunIndex] = typeclasses;
                    })

                    // console.log('构造的数据结构', localItem)
                    wx.setStorageSync('localItem', localItem)
                    this.setData({
                        myAllItem: localItem,
                    })
                }).catch((err) => {
                    console.log(err);
                })
                //只遍历 主食材的id， 确定主食材是否确实，以便展示替换的菜谱
            console.log('mainProductId', mainProductId)
            mainProductId.forEach((i, num) => {
                that.getThreeProducts(i, shopId, menuid).then((res) => {
                    //先确定该菜谱是否 缺失主材，只有一个主食材时
                    console.log('ssssssssssss', res)
                        //这一步是删除 缺失主材的id，保留存在的主材id
                    if (res[0].missing && res[0].missing == true) {
                        repalceId = repalceId.filter((ele) => {
                            return ele !== i
                        })
                        that.replaceCookbooks(repalceId, shopId).then((res) => {


                            // let replaceCookbooks = 'replaceCookbooks' + '[' + meunIndex + ']'
                            let replaceCookbooks = []
                            console.log('替换的菜谱', res)
                            replaceCookbooks[meunIndex] = res;
                            that.setData({
                                replaceCookbooks: replaceCookbooks
                            })
                        })
                    } else {

                    }
                    console.log('repalceId', repalceId)

                });
            })


        }

    },
    //新版替换菜谱 根据主材分类IDS 查找该商家 该主材 主材齐全的菜谱
    //触发条件：菜谱至少有一个主材缺失，传入为缺失的主食材id
    replaceCookbooks(ids, shop_id) {
        ids = ids.join(",");
        return new Promise(function(resolve, reject) {
            http.request({
                url: api.replaceCookbooks,
                method: "POST",
                data: {
                    ids: ids,
                    shop_id: shop_id
                },
                success: (res) => {
                    console.log('replaceCookbooks', res)
                    if (res.code == 200) {
                        const data = res.data
                        resolve(data);
                    } else if (res.data.code == 401) {
                        console.log('该商家没有可替换的菜谱')
                        reject()
                    }
                },
                fail: (res) => {
                    console.log('error', res)
                }
            })
        })


    },
    //遍历当前菜谱辅料不存在时
    isAllExists() {
        let existState = [];
    },
    toMeunDetail(e) {
        let id = e.currentTarget.dataset.id;
        let signShop = true; //来自店铺 替换查看详情
        wx.navigateTo({
            url: `/pages/video/video?id=${id}&signShop=${signShop}`
        })
    },
    //替换 操作当前菜谱, 一次只有一个
    replaceCurrentMeun(e) {
        let currentProductId = [];
        let that = this;
        //替换当前页菜谱，替换storage选择的菜单
        let tindex = e.currentTarget.dataset.tindex; //父级索引
        let findex = e.currentTarget.dataset.findex;
        let replaceCookbooks = this.data.replaceCookbooks[tindex];
        let item = replaceCookbooks[findex];

        let singleShopMenus = this.data.singleShopMenus[tindex];
        let myAllItem = this.data.myAllItem;
        console.log('singleShopMenus', singleShopMenus)

        let content = `${item.name} 替换 ${singleShopMenus.name}`;

        let meunId = item.id;
        wx.showModal({
            title: '确定使用',
            content: content,
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#7D7B7B',
            confirmText: '确定',
            confirmColor: '#EB4942',
            success: function(res) {
                if (res.confirm) {
                    console.log('用户点击确定')
                    let newBooks = Object.assign(singleShopMenus, item); //替换后的新的菜谱
                    let newShopMenus = 'singleShopMenus' + '[' + tindex + ']'
                    that.setData({
                        [newShopMenus]: newBooks
                    });

                    http.request({
                        url: api.getCookClass,
                        method: "POST",
                        data: {
                            ids: meunId, //多个菜谱id
                        },
                        success: (res) => {
                            const data = res.data;
                            console.log('替换的菜谱', data)
                            let typeclasses = data[0].typeclasses;
                            typeclasses.forEach((item, i) => {
                                currentProductId.push(item.classes_id)
                                    // //单品分类的id -循环请求,新增区分主材与辅材
                                    // if (item.classes_type == 0) { //增加主食材id
                                    //   mainProductId.push(item.classes_id)
                                    //   repalceId.push(item.classes_id)
                                    // } else if (item.classes_type == 1) {
                                    //   minorProductId.push(item.classes_id)
                                    // }
                            })

                            console.log("?????", currentProductId)
                            that.getAllProducts(currentProductId, shopId, meunId, tindex, typeclasses)
                        },
                        fail: (res) => {
                            console.log('error', res)
                        }
                    })

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            },

        })



    },
    getAllProducts(currentProductId, shopId, menuid, tindex, typeclasses) {
        let myAllItem = this.data.myAllItem;


        // let myAllItem = 'myAllItem' + '[' + tindex + ']'
        //依据接口，遍历所有的单品id——循环请求
        let promises = currentProductId.map((i, num) => {
            //可售卖菜谱
            return this.getThreeProducts(i, shopId, menuid)
        })
        Promise.all(promises).then((allData) => {
            console.log('????allData', allData)

            allData.forEach((res, num) => {
                if (res[0].missing && res[0].missing == true) {
                    typeclasses[num].missing = true
                } else {
                    typeclasses[num].missing = false
                }
                typeclasses[num].son = res
                myAllItem[tindex] = typeclasses
            })



            this.setData({
                myAllItem,
                replaceCookbooks: []
            })

            // // console.log('构造的数据结构', localItem)
            // wx.setStorageSync('localItem', localItem)

        }).catch((err) => {
            console.log(err);
        })
    },

    onUnload: function() {
        wx.removeStorageSync('localItem')
        sss = [] //下单时过渡数组
    },
    onHide: function() {
        sss = [] //下单时过渡数组
    }
});